/*
 * 组件注释
 * @Author: machinist_wq
 * @Date: 2022-05-03 12:50:21
 * @LastEditors: machinist_wq
 * @LastEditTime: 2022-06-30 10:26:35
 * @Description: 打包环境配置
 * 人生无常！大肠包小肠......
 */
const path = require("path");
const os = require("os");
const nodeExternals = require("webpack-node-externals");
const webpackConfigBase = require("./webpack.base.config");
const TerserJSPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
// const WorkboxWebpackPlugin = require("workbox-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const { merge } = require("webpack-merge");
// cpu核数

const threads = os.cpus().length;

function resolve(relatedPath) {
  return path.join(__dirname, relatedPath);
}

const webpackConfigProd = {
  mode: "production",
  output: {
    filename: "[chunkhash:10][name].index.js",
    path: resolve("../dist"),
    clean: true,
    publicPath: "auto",
    library: {
      root: "componentLibrary",
      amd: "component-library",
    },
    libraryTarget: "umd",
  },
  // 若不需要调试打包文件则使用false
  devtool: "source-map",
  optimization: {
    minimize: true,
    minimizer: [
      // 压缩js代码
      new TerserJSPlugin({
        // 多进程压缩
        parallel: threads, // 开启多进程压缩
        terserOptions: {
          compress: {
            drop_console: true, // 删除所有的 `console` 语句
            drop_debugger: true, // 删除所有的 `debugger` 语句
          },
        },
      }),
      //压缩css代码
      new CssMinimizerPlugin(),
    ],
    // 代码分割
    splitChunks: {
      chunks: "all",
    },
    // 模块互相引用的缓存
    runtimeChunk: {
      name: entrypoint => `runtime~${entrypoint.name}.js`,
    },
  },
  externals: [nodeExternals()],

  plugins: [
    // TODO 这个插件不太好使
    // new WorkboxWebpackPlugin.GenerateSW({
    //   // 这些选项帮助快速启用 ServiceWorkers
    //   // 不允许遗留任何“旧的” ServiceWorkers
    //   clientsClaim: true,
    //   skipWaiting: true,
    // }),
    new CleanWebpackPlugin(), //每次执行都将清空一下./dist目录
  ],
};
module.exports = merge(webpackConfigBase, webpackConfigProd);
